package com.UnionPayCenter.user.service.impl;

import com.UnionPayCenter.distribution.dto.DistributionBaseDTO;
import com.UnionPayCenter.entity.ShopInfoEntity;
import com.UnionPayCenter.entity.vo.UserVo;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.mapper.UserMapper;
import com.UnionPayCenter.service.IUserService;
import com.UnionPayCenter.service.serviceImpl.UserServiceImpl;
import com.UnionPayCenter.user.dto.WechatRegisterDTO;
import com.UnionPayCenter.user.service.UserOperatorService;
import com.UnionPayCenter.util.HttpUtil;
import com.UnionPayCenter.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

/**
 * @author noah
 * @since 1.0.0, 2019/09/18
 */
@Service
@Primary
public class UserOperatorServiceImpl  extends UserServiceImpl implements UserOperatorService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserService userService;



    @Override
    public UserVo WechatRegister(WechatRegisterDTO wechatRegisterDTO) {

            String openId = wechatRegisterDTO.getOpenid();
            String unionId = wechatRegisterDTO.getUnionid();
            String sessionKey = wechatRegisterDTO.getSessionKey();
            Integer parentId = wechatRegisterDTO.getParentId();
            Integer shopId = wechatRegisterDTO.getShopId();
            UserVo user = userMapper.selectByOpenid(shopId, openId);
            if (user == null) {
                //用户不存在 添加
                user = new UserVo();
                user.setShopId(shopId);
                user.setOpenid(openId);
                user.setUnionid(unionId);
                user = this.insertUser(user, parentId, false);
                //已注册用户查询余额，会员等级，等级折扣，优惠券数量
                user = this.getInfo(user);
                DistributionBaseDTO baseDTO = new DistributionBaseDTO();
                baseDTO.setBId(Long.valueOf(shopId));
                baseDTO.setShopId(Long.valueOf(shopId));
                distributionOperatorService.distributionInitUser(baseDTO, parentId == null ? null : Long.valueOf(parentId),
                        Long.valueOf(user.getUserId()));
            } else {
                //已注册用户查询余额，会员等级，等级折扣，优惠券数量
                user = this.getInfo(user);
            }
            setEnableDistribution(user, shopId);
            user.setSessionKey(sessionKey);
            return user;

    }
}
